/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.module.login.presenter

import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import top.stime21.myneighbours.api.LocalDataManager
import top.stime21.myneighbours.base.MvpBasePrensenter
import top.stime21.myneighbours.module.login.LoginContract
import top.stime21.myneighbours.module.login.model.LoginModelImpl
import java.util.concurrent.TimeUnit

/**
 * Author: czmc  Email: @tuwan21.com
 * Version:	1.0  Date:3/3/2018
 */
class LoginPrensenterImpl(override val view: LoginContract.View) : MvpBasePrensenter<LoginContract.View, LoginContract.Model>(), LoginContract.Presenter {


    override val model: LoginContract.Model
        get() = LoginModelImpl()
    private val SMS_COUNT:Long = 60
    private var smsTasking: Boolean = false

    override fun sendSms(mobile: String) {
        addSubscription(model.sendSms(mobile).subscribe({ result ->

            if (smsTasking) return@subscribe
            smsTasking = true
            if (result.isSuccess) {
                addSubscription(Observable
                        .interval(0, 1, TimeUnit.SECONDS)
                        .take(SMS_COUNT+1)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .map({ now -> SMS_COUNT - now })
                        .subscribe({ time ->
                            Logger.i("time = " + time)
                            view.onSMSCount(time, time < 1)
                            if (time < 1) {
                                smsTasking = false
                            }
                        }))
            }else{
                view.showToast("发送验证码失败")
            }
        }, {
                t->
                Logger.e(t.toString())
                view.showToast("发送验证码失败")
        }))
    }

    override fun login(mobile: String, vcode: String) {
        addSubscription(model.login(mobile, vcode).subscribe({
            r->
            if(r.isSuccess){
                if(r.data!=null){
                    LocalDataManager.ins().setUser(view.context(), r.data!!)
                    view.onLoginSuccess()
                }else{
                    view.showToast("获取用户信息错误")
                }
            }else{
                view.showToast("验证码不正确")
            }
        }, {
            t->
            Logger.e(t.toString())
            view.showToast("登陆失败")
        }))
    }

}